package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.pojo.entity.BorrowerAttach;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.BorrowerApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerVO;
import com.atguigu.srb.core.service.BorrowerAttachService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author Atguigu
 * @since 2023-03-25
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {
    @Resource
    UserInfoService userInfoService;
    @Resource
    DictService dictService;
    @Resource
    BorrowerAttachService borrowerAttachService;
    @Override
    public void saveBorrowerVo(BorrowerVO borrowerVO, String token) {
        Long userId = JwtUtils.getUserId(token);
        UserInfo userInfo = userInfoService.getById(userId);
        //1、保存借款人数据
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO , borrower);
        borrower.setMobile(userInfo.getMobile());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setName(userInfo.getName());
        //认证中状态
        borrower.setStatus(1);
        borrower.setUserId(userId);
        this.save(borrower);
        //2、保存借款人附件图片数据
        List<BorrowerAttach> attachs = new ArrayList<>();
        String idCard1 = borrowerVO.getIdCard1();
        String idCard2 = borrowerVO.getIdCard2();
        String car = borrowerVO.getCar();
        String house = borrowerVO.getHouse();
        if(StringUtils.isNotEmpty(idCard1)){
            BorrowerAttach borrowerAttach = new BorrowerAttach();
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttach.setImageUrl(idCard1);
            borrowerAttach.setImageType("idCard1");
            borrowerAttach.setImageName("身份证正面");
            attachs.add(borrowerAttach);
        }
        if(StringUtils.isNotEmpty(idCard2)){
            BorrowerAttach borrowerAttach = new BorrowerAttach();
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttach.setImageUrl(idCard2);
            borrowerAttach.setImageType("idCard2");
            borrowerAttach.setImageName("身份证反面");
            attachs.add(borrowerAttach);
        }
        if(StringUtils.isNotEmpty(car)){
            BorrowerAttach borrowerAttach = new BorrowerAttach();
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttach.setImageUrl(car);
            borrowerAttach.setImageType("car");
            borrowerAttach.setImageName("车");
            attachs.add(borrowerAttach);
        }
        if(StringUtils.isNotEmpty(house)){
            BorrowerAttach borrowerAttach = new BorrowerAttach();
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttach.setImageUrl(house);
            borrowerAttach.setImageType("house");
            borrowerAttach.setImageName("房产证");
            attachs.add(borrowerAttach);
        }
        if(CollectionUtils.isNotEmpty(attachs)){
            borrowerAttachService.saveBatch(attachs);
        }

    }

    @Override
    public void listBorrowersByKey(Page page, String key) {
        LambdaQueryWrapper<Borrower> wrapper = Wrappers.lambdaQuery(Borrower.class);
        if(StringUtils.isNotEmpty(key)){
            wrapper.like(Borrower::getName , key)
                    .or()
                .like(Borrower::getMobile , key)
                    .or()
                .like(Borrower::getIdCard , key);
        }
        this.page(page , wrapper);
    }
    //根据借款人id查询查询借款人详情
    @Override
    public BorrowerVO queryBorrowerVOById(Long id) {
        Borrower borrower = this.getById(id);
        List<BorrowerAttach> attaches = borrowerAttachService.list(Wrappers.lambdaQuery(BorrowerAttach.class)
                .eq(BorrowerAttach::getBorrowerId, id));
        //设置附件
        BorrowerVO borrowerVO = new BorrowerVO();
        borrowerVO.setBorrowerAttaches(attaches);
        //设置borrower对象的属性值给vo
        BeanUtils.copyProperties(borrower , borrowerVO);

        //设置数据字典

        Integer returnSource = borrower.getReturnSource();
        Integer contactsRelation = borrower.getContactsRelation();
        Integer industry = borrower.getIndustry();
        Integer income = borrower.getIncome();
        Integer education = borrower.getEducation();
        //数据字典： 根据某个二级数据字典的 value值+自己的一级数据字典的dictCode 查询自己的标题
        String returnSourceStr = dictService.getDictNameByDictCodeAndValue("returnSource", returnSource);
        String relationStr = dictService.getDictNameByDictCodeAndValue("relation", contactsRelation);
        String industryStr = dictService.getDictNameByDictCodeAndValue("industry", industry);
        String incomeStr = dictService.getDictNameByDictCodeAndValue("income", income);
        String educationStr = dictService.getDictNameByDictCodeAndValue("education", education);
        Map<String,String> map = new HashMap<>();
        map.put("returnSource",returnSourceStr);
        map.put("relation",relationStr);
        map.put("industry",industryStr);
        map.put("income",incomeStr);
        map.put("education",educationStr);
        borrowerVO.setDicts(map);
        return borrowerVO;
    }

    @Override
    public void approval(BorrowerApprovalVO borrowerApprovalVO) {
        //获取审批状态：
        Integer status = borrowerApprovalVO.getStatus();
        //获取借款人id
        Long borrowerId = borrowerApprovalVO.getBorrowerId();
        //查询借款人数据：查询到会员id
        Borrower borrower = this.getById(borrowerId);
        //更新借款人审批状态
        borrower.setStatus(status);
        this.updateById(borrower);
        //更新会员：
        UserInfo userInfo = userInfoService.getById(borrower.getUserId());
        userInfo.setBorrowAuthStatus(status);//设置借款人审批状态
        if(status.intValue()==2){//数值型包装类对象和数字直接==比较 可能会出现不相等情况
            //累加审批通过的积分
            Integer total = 0;
            Integer infoIntegral = borrowerApprovalVO.getInfoIntegral();//基本积分
            Boolean isCarOk = borrowerApprovalVO.getIsCarOk();
            Boolean isHouseOk = borrowerApprovalVO.getIsHouseOk();
            Boolean isIdCardOk = borrowerApprovalVO.getIsIdCardOk();
            if(infoIntegral!=null){
                total+=infoIntegral;
            }
            if(isIdCardOk){
                total+=30;
            }
            if(isCarOk){
                total+=60;
            }
            if(isHouseOk){
                total+=100;
            }
            userInfo.setIntegral(userInfo.getIntegral()+total);
        }
        userInfoService.updateById(userInfo);
    }
    //根据userInfo会员id查询借款人详情
    @Override
    public BorrowerVO queryBorrowerVOByUserId(Long userId) {
        Borrower borrower = this.getOne(Wrappers.lambdaQuery(Borrower.class)
                .eq(Borrower::getUserId, userId)
                .select(Borrower::getId));//只查询Borrower的id
        BorrowerVO borrowerVO = this.queryBorrowerVOById(borrower.getId());
        return borrowerVO;
    }
}
